package com.emotionalEnvelope.edu.config;


import com.emotionalEnvelope.edu.core.ControllerException;
import com.emotionalEnvelope.edu.util.MyTokenUtil;
import org.json.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author lqq
 * @version 1.0
 * @data 2022/9/9 14:32
 */

@Component
public class MyTokenInterceptor extends ControllerException implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println(request.getRequestURI());
        if (request.getMethod().equals("OPTIONS")
                || request.getRequestURI().equals("/index.html")) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }//qe
        response.setCharacterEncoding("utf-8");
        //前端vue将token添加在请求头中
        String token = request.getHeader("token");
        if (token != null) {
            String result = MyTokenUtil.verify(token);
            if (StringUtils.hasLength(result)) {
                System.out.println("通过拦截器");
                return true;
            }
        }

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            JSONObject json = new JSONObject();
            json.put("msg", "token认证失败!");
            json.put("code", "50000");
            response.getWriter().append(json.toString());
            System.out.println("认证失败，未通过拦截器!!!");
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(500);
            return false;
        }
        return false;
    }


}
